package k8s

import (
	"strings"
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes/scheme"
	"io/ioutil"
)


var DEFAULT_LOG_LINE  = int64(100)

type LogInfo struct {
	PodName string			`json:"podName"`
	Containers []string		`json:"containers"`
	LogLines []LogLine 		`json:"logLines"`
}


type LogLine struct {
	Timestamp string 		`json:"timestamp"`
	Content   string       	`json:"content"`
}

func ParseToLogLines(rawLogs string) (LogLines []LogLine) {

	for _, line := range strings.Split(rawLogs, "\n") {
		if line != "" {
			startsWithDate := ('0' <= line[0] && line[0] <= '9') //2017-...
			idx := strings.Index(line, " ")
			if idx > 0 && startsWithDate {
				timestamp := line[0:idx]
				content := line[idx+1:]
				LogLines = append(LogLines, LogLine{Timestamp: timestamp, Content: content})
			} else {
				LogLines = append(LogLines, LogLine{Timestamp: "0", Content: line})
			}
		}
	}
	return LogLines
}

func GetKubernetesPodLogs(ns string,podName string) (podLogs LogInfo,err error) {
	pod,_ := clientset.CoreV1().Pods(ns).Get(podName,metav1.GetOptions{})

	podLogs.PodName = pod.Name
	for _,c := range pod.Spec.Containers {
		podLogs.Containers = append(podLogs.Containers,c.Name)
	}

	logOption := v1.PodLogOptions{
		Container: pod.Spec.Containers[0].Name,
		Follow: false,
		Previous: false,
		Timestamps: true,
		TailLines: &DEFAULT_LOG_LINE,
	}

	podLogReader,err := clientset.CoreV1().
		RESTClient().
		Get().
		Namespace(ns).
		Name(podName).
		Resource("pods").
		SubResource("log").
		VersionedParams(&logOption,scheme.ParameterCodec).
		Stream()

	if err != nil {
		fmt.Println("get pod's log error is" ,err.Error())
		return
	}
	defer podLogReader.Close()
	result, err := ioutil.ReadAll(podLogReader)
	if err != nil {
		fmt.Println("this error is",err.Error())
	}
	//fmt.Println(string(result))

	podLogs.LogLines = ParseToLogLines(string(result))
	return
}
